#!/usr/bin/env python
__version__ = "0.01"

from xml.sax import expatreader, xmlreader, saxutils
from StringIO import StringIO

#XOP_NS = 'http://www.w3.org/2003/12/xop/include'
#XOP_MT_SUFFIX = '_xop+xml'


class CairoGladeParser(expatreader.ExpatParser):
    def parse(self, source):
        self._source = (source)
        self.reset()
        self._cont_handler.setDocumentLocator(expatreader.ExpatLocator(self))
        return xmlreader.IncrementalParser.parse(self, self._source)
        
    def setContentHandler(self, handler):
        return expatreader.ExpatParser.setContentHandler(
          self, CairoGladeHandlerWrapper(handler, self))


class CairoGladeHandlerWrapper:
    def __init__(self, handler, parser):
        self._handler = handler
        self._parser = parser
        
    def __getattr__(self, attr):    # bit of a hack; maybe a metaclass instead?
        return getattr(self._handler, attr)
                
    def startElementNS(self, name, qname, attrs):
        #if name == (XOP_NS, 'Include'):
        #    if hasattr(self._handler, 'binary'):
        #        self._handler.binary(self._include(attrs[(None, 'href')]))
        #    else:
        #        self._handler.characters(base64.encodestring(self._include(attrs[(None, 'href')]))[:-1])
        #else:
        self._handler.startElementNS(name, qname, attrs)

    def endElementNS(self, name, qname):
        #if name == (XOP_NS, 'Include'):
        #    pass
        #else:
        self._handler.endElementNS(name, qname)
            
    def _include(self, href):
        if href.lower()[:4] == 'cid:':
            return self._parser._partsByID["<%s>" % href[4:]].get_payload(decode=1)
        else:
            return self._parser._partsByCL[href].get_payload(decode=1)
            

def create_parser(*args, **kwargs):
    return CairoGladeParser(*args, **kwargs)


def test(doc):
    """Given a XOP Package, emit an XML 1.0 serialization of its Optimized Infoset"""
    from xml import sax
    from xml.sax import saxutils
    dh = saxutils.XMLGenerator()
    p = CairoGladeParser()
    p.setContentHandler(dh)
    #p.setFeature(sax.handler.feature_namespaces, 1)
    p.parse(doc)


if __name__ == '__main__':
#     import profile
#     profile.run('test(StringIO(doc))')

    import sys
    test(open("test.xml","r"))

